package com.zscat.mallplus.controller.common;

import com.zscat.mallplus.annotation.IgnoreAuth;
import com.zscat.mallplus.exception.ApiMallPlusException;
import com.zscat.mallplus.util.OssAliyunUtil;
import com.zscat.mallplus.utils.CommonResult;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * 通用请求处理
 *
 * @author loop.fu
 */
@RestController
@RequestMapping("/api/common")
public class CommonController {

    private static final Logger log = LoggerFactory.getLogger(CommonController.class);

    @Autowired
    OssAliyunUtil aliyunOSSUtil;

    /**
     * 上传文件
     *
     * @param file
     * @return
     */
    @IgnoreAuth
    @PostMapping("/aliyun/upload")
    public CommonResult upload(@RequestParam("file") MultipartFile file) {
        try {
            String url = aliyunOSSUtil.upload(file);
            return new CommonResult().success(url);
        } catch (ApiMallPlusException e) {
            return new CommonResult().failed(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return new CommonResult().failed("系统错误，请稍后再试！");
        }
    }

    /**
     * 多文件上传文件
     *
     * @param file
     * @return
     */
    @IgnoreAuth
    @PostMapping("/aliyun/uploads")
    public CommonResult uploads(@RequestPart("file") MultipartFile[] file) throws Exception {
        try {
            StringBuffer stringBuffer = new StringBuffer();
            if (file != null && file.length > 0) {
                for (int i = 0; i < file.length; i++) {
                    stringBuffer.append(aliyunOSSUtil.upload(file[i]) + ",");
                }
            }
            return new CommonResult().success(stringBuffer);
        } catch (ApiMallPlusException e) {
            return new CommonResult().failed(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return new CommonResult().failed("系统错误，请稍后再试！");
        }
    }

}
